/* @flow */

import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'


// 获取组件的名字
function getComponentName(opts) {
  return opts && (opts.Ctor.options.name || opts.tag)
}
// 判断 组件的名字 是否满足 include 或 exclude
function matches(pattern, name) { // 'qqq,www'
  if (Array.isArray(pattern)) {
    return pattern.indexOf(name) > -1
  } else if (typeof pattern === 'string') {
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false
}

function pruneCache(keepAliveInstance, filter) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const entry = cache[key]
    if (entry) {
      const name = entry.name
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

function pruneCacheEntry(
  cache,
  key,
  keys,
  current
) {
  const entry = cache[key]
  if (entry && (!current || entry.tag !== current.tag)) {
    entry.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}

const patternTypes = [String, RegExp, Array]

export default {
  name: 'keep-alive',
  abstract: true,

  // props: ['include', 'exclude', 'max'],
  props: {
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },

  methods: {
    cacheVNode() {
      const { cache, keys, vnodeToCache, keyToCache } = this
      if (vnodeToCache) {
        const { tag, componentInstance, componentOptions } = vnodeToCache
        cache[keyToCache] = {
          name: getComponentName(componentOptions),
          tag,
          componentInstance,
        }
        keys.push(keyToCache)
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
        this.vnodeToCache = null
      }
    }
  },
  // data() {
  //   return {
  //     cache: Object.create(null),
  //     keys: []
  //   }
  // },

  created() {
    this.cache = Object.create(null) // 存储需要缓存的哪些实例的对象
    this.keys = []// 存储 缓存的实例对应的key
  },

  destroyed() {
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

  mounted() {
    this.cacheVNode()
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
      pruneCache(this, name => !matches(val, name))
    })
  },
  // watch: {
  //   include() { },
  //   exclude() { }
  // },

  updated() {
    this.cacheVNode()
  },

  render() {
    const slot = this.$slots.default // 获取keep-alive 包含的内容
    const vnode = getFirstComponentChild(slot)// 获取插槽里的第一个组件实例
    const componentOptions = vnode && vnode.componentOptions// 组件的一些属性
    if (componentOptions) {
      // check pattern
      const name = getComponentName(componentOptions) // keep 包含的那个组件的名字
      const { include, exclude } = this
      if (
        // not included
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name))
      ) {
        // 若要渲染的那个组件 不满足 include 或者满足 exclude  那么直接使用新创造的实例
        return vnode
      }
      // 能走到这里的 证明 要加载的组件是需要缓存的

      const { cache, keys } = this
      const key = vnode.key == null
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
      if (cache[key]) {
        // 若缓存对象中有这一项 那么就直接使用缓存的组件实例
        vnode.componentInstance = cache[key].componentInstance
        // make current key freshest
        // LRU 算法
        remove(keys, key)
        keys.push(key)
        // 因为keys里边去删除多余的key的时候 是从第一个开始删除的
      } else {
        // 缓存对象中没有 当前实例  那么就要把当前实例缓存起来
        this.vnodeToCache = vnode
        this.keyToCache = key
      }

      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
}
